
/*
 *                    BioJava development code
 *
 * This code may be freely distributed and modified under the
 * terms of the GNU Lesser General Public Licence.  This should
 * be distributed with the code.  If you do not have a copy,
 * see:
 *
 *      http://www.gnu.org/copyleft/lesser.html
 *
 * Copyright for this code is held jointly by the individual
 * authors.  These should be listed in @author doc comments.
 *
 * For more information on the BioJava project and its aims,
 * or to join the biojava-l mailing list, visit the home page
 * at:
 *
 *      http://www.biojava.org/
 *
 * @author Thomas Down
 *
 */
package dasregistry;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;

/**
 * Filter object that rewrites inbound HTTP requests with modified serverName
 * and serverPort attributes.  Typical usage is in situations where a back-end
 * servlet container is running behind an HTTP proxy, but the servlets need
 * to know their externally-visible hostname rather than the name of the
 * internal servlet-running machine.
 *
 * @author Thomas Down
 */
public class ProxyFilter implements Filter {
    private String proxyHost;
    private int proxyPort;
    
    public void init(FilterConfig config) 
        throws ServletException
    {
        String h = config.getInitParameter("proxy-host");
        String p = config.getInitParameter("proxy-port");
        if (h == null) {
            throw new ServletException("Must specify proxy-host");
        }
        if (p == null) {
            throw new ServletException("Must specify proxy-port");
        }
        proxyHost = h;
        try {
            proxyPort = Integer.parseInt(p);
        } catch (NumberFormatException ex) {
            throw new ServletException("Invalid proxy-port " + p);
        }
    }
    
    public void destroy() {
    }
    
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) 
        throws IOException, ServletException
    {
        if (request instanceof HttpServletRequest) {
            request = new HttpServletRequestWrapper((HttpServletRequest) request) {
                public String getServerName() {
                    return proxyHost;
                }
                
                public int getServerPort() {
                    return proxyPort;
                }
                
            } ;
        }
        chain.doFilter(request, response);
    }
}
